import { Request, Response } from 'express';
import { UserService } from '../services/userService';

const userService = new UserService();

// 获取所有管理员用户
export const getAdminUsers = async (req: Request, res: Response) => {
  try {
    const { page, limit, keyword, role, status } = req.query;
    
    const result = await userService.getUsers({
      page: page ? parseInt(page as string) : 1,
      limit: limit ? parseInt(limit as string) : 10,
      keyword: keyword as string,
      role: role as string,
      status: status !== undefined ? status === 'true' : undefined,
    });

    res.json({ 
      success: true, 
      data: result.users,
      pagination: {
        total: result.total,
        page: result.page,
        limit: result.limit,
        totalPages: result.totalPages,
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '获取用户失败',
      error 
    });
  }
};

// 新增管理员用户
export const createAdminUser = async (req: Request, res: Response) => {
  try {
    const { username, email, password, role, status } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({ 
        success: false, 
        message: "用户名和密码不能为空" 
      });
    }

    const user = await userService.createUser({
      username,
      email,
      password,
      role: role || 'user',
      status: status !== undefined ? status : true,
    });

    res.status(201).json({ 
      success: true, 
      data: user,
      message: '用户创建成功'
    });
  } catch (error) {
    console.error('创建用户失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '创建用户失败',
      error 
    });
  }
};

// 编辑管理员用户
export const updateAdminUser = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { username, email, role, status, password } = req.body;

    const user = await userService.updateUser(parseInt(id), {
      username,
      email,
      role,
      status,
      password,
    });

    res.json({ 
      success: true, 
      data: user,
      message: '用户更新成功'
    });
  } catch (error) {
    console.error('更新用户失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '更新用户失败',
      error 
    });
  }
};

// 软删除管理员用户
export const deleteAdminUser = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const deleteBy = (req as any).user?.id; // 获取当前操作用户ID
    
    await userService.deleteUser(parseInt(id), deleteBy);
    
    res.json({ 
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '删除用户失败',
      error 
    });
  }
};

// 获取单个用户详情
export const getAdminUserById = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const user = await userService.getUserById(parseInt(id));
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({ 
      success: true, 
      data: user
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '获取用户详情失败',
      error 
    });
  }
};

// 获取用户统计信息
export const getUserStats = async (req: Request, res: Response) => {
  try {
    const stats = await userService.getUserStats();
    
    res.json({ 
      success: true, 
      data: stats
    });
  } catch (error) {
    console.error('获取用户统计失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '获取用户统计失败',
      error 
    });
  }
};

// 检查用户名是否可用
export const checkUsernameAvailability = async (req: Request, res: Response) => {
  try {
    const { username, excludeId } = req.query;
    
    if (!username) {
      return res.status(400).json({
        success: false,
        message: '用户名参数不能为空'
      });
    }

    const isAvailable = await userService.isUsernameAvailable(
      username as string,
      excludeId ? parseInt(excludeId as string) : undefined
    );

    res.json({ 
      success: true, 
      data: { available: isAvailable }
    });
  } catch (error) {
    console.error('检查用户名可用性失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '检查用户名可用性失败',
      error 
    });
  }
};

// 检查邮箱是否可用
export const checkEmailAvailability = async (req: Request, res: Response) => {
  try {
    const { email, excludeId } = req.query;
    
    if (!email) {
      return res.status(400).json({
        success: false,
        message: '邮箱参数不能为空'
      });
    }

    const isAvailable = await userService.isEmailAvailable(
      email as string,
      excludeId ? parseInt(excludeId as string) : undefined
    );

    res.json({ 
      success: true, 
      data: { available: isAvailable }
    });
  } catch (error) {
    console.error('检查邮箱可用性失败:', error);
    res.status(500).json({ 
      success: false, 
      message: error instanceof Error ? error.message : '检查邮箱可用性失败',
      error 
    });
  }
};
